const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const { User, Class } = require('../models');

// 获取用户信息
router.get('/info', auth, async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      include: [{
        model: Class,
        attributes: ['name', 'code']
      }]
    });

    res.json({
      success: true,
      userInfo: {
        id: user.id,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl,
        role: user.role,
        className: user.Class?.name,
        classCode: user.Class?.code
      }
    });

  } catch (error) {
    console.error('Get user info error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

// 更新用户信息
router.put('/info', auth, async (req, res) => {
  try {
    const { nickname, avatarUrl } = req.body;
    
    await req.user.update({
      nickname: nickname || req.user.nickname,
      avatarUrl: avatarUrl || req.user.avatarUrl
    });

    res.json({
      success: true,
      message: '更新成功'
    });

  } catch (error) {
    console.error('Update user info error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;